package cn.uncode.springcloud.gateway.route;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.uncode.springcloud.gateway.canary.DefaultCanaryStrategy;
import cn.uncode.springcloud.gateway.ribbon.RibbonContextHolder;

import reactor.core.publisher.Flux;


@RestController
@RequestMapping("/route")
public class DynamicRouteController {
	


    @Autowired
    private DynamicRouteService dynamicRouteService;
    
    @Autowired 
    private RouteDefinitionLocator routeDefinitionLocator;
    
    @Autowired
    private DefaultCanaryStrategy defaultCanaryStrategy;
    

    /**
     * 获取网关所有的路由信息
     * @return
     */
    @GetMapping("/all")
    public Flux<RouteDefinition> getRouteDefinitions(){
        return routeDefinitionLocator.getRouteDefinitions();
    }

    
    @GetMapping("/refresh")
    public String refresh(){
    	String rt = dynamicRouteService.refresh(false);
    	if(StringUtils.isNotBlank(rt)) {
    		return rt;
    	}
    	return "success";
    }
    
    @GetMapping("/forceRefresh")
    public String forceRefresh(){
    	String rt = dynamicRouteService.refresh(true);
    	if(StringUtils.isNotBlank(rt)) {
    		return rt;
    	}
    	return "success";
    }
    
    @GetMapping("/canaryRefresh")
    public String canaryRefresh(){
    	String rt = dynamicRouteService.canaryRefresh();
    	if(StringUtils.isNotBlank(rt)) {
    		return rt;
    	}
    	return "success";
    }
    
    @GetMapping("/canaryInfo")
    public String canaryInfo(){
    	StringBuffer sb = new StringBuffer();
    	sb.append("灰度节点信息: ").append(RibbonContextHolder.getFlag2AppName().toString()).append(",");
    	sb.append("Ip2flag: ").append(defaultCanaryStrategy.getIp2flag().toString()).append(",");
    	sb.append("KeyInRequest2flag: ").append(defaultCanaryStrategy.getKeyInRequest2flag().toString()).append(",");
    	sb.append("KeyInRequest2value: ").append(defaultCanaryStrategy.getKeyInRequest2value().toString()).append(",");
    	sb.append("KeyInSession2flag: ").append(defaultCanaryStrategy.getKeyInSession2flag().toString()).append(",");
    	sb.append("KeyInSession2value: ").append(defaultCanaryStrategy.getKeyInSession2value().toString()).append(".");
    	if(sb.length() > 0) {
    		return sb.toString();
    	}
    	return "success";
    }
    

}
